package rpc.client;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import common.Common;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author daxue0929
 * @date 2023/2/17
 */

public class ClientRPC {

    private final static String RPC_QUEUE_NAME = "rpc_queue";

    public static void main(String[] args) throws IOException, InterruptedException {
        Channel channel = Common.getChannel();

        String replyQueueName = channel.queueDeclare().getQueue();
        System.out.println(replyQueueName);

        /*指定一个唯一标识，用于将RPC响应与请求关联起来*/
        final String corrId = UUID.randomUUID().toString();

        /*定义消息属性，指定唯一标识corrId与回调队列*/
        AMQP.BasicProperties props = new AMQP.BasicProperties
            .Builder()
            .correlationId(corrId)
            .replyTo(replyQueueName)
            .build();

        String message = "10";
        channel.basicPublish("", RPC_QUEUE_NAME ,props, message.getBytes());

        final BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);

        channel.basicConsume(replyQueueName,true, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                /*检查corrId是否匹配*/
                if (properties.getCorrelationId().equals(corrId)){
                    response.offer(new String(body,"UTF-8"));
                }
            }
        });
        String rpcResponse = response.take();
        System.out.println("队列：" + rpcResponse);
    }
}
